import React, { Component, Fragment } from 'react'
import dateFormat from 'dateformat'
import {
  ContentHeader,
  ContentHeaderName,
  ContentHeaderExit,
  ContentHeader2,
  ContentHeaderurl,
  ContentHeaderTime,
} from '../../../css/header'
import {
  ACTION_DELETE_ROUTER,
  ACTION_CHANGE_ACTIVE_INDEX,
} from '../../../store/actioncreaters'
import { connect } from 'react-redux'
import './Header.less'
//路由跳转
import { withRouter } from 'react-router-dom'
class HeaderComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      message: '头部',
      nowTime: null,
      urldata: JSON.parse(sessionStorage.getItem('urldata')) || [
        { name: '首页', url: '/home' },
      ],
      nowUrl: '', //当前路径
      activenum: 0, //面包屑导航活跃类序号
      dingshi: null, //定时
    }
    this.goEnd = this.goEnd.bind(this)
    this.changeUrl = this.changeUrl.bind(this)
    this.closeUrl = this.closeUrl.bind(this)
  }
  componentDidMount() {
    this.dataformat()
    this.activeurlnum()
  }
  componentWillReceiveProps(nextProps) {
    //监听路由
    if (nextProps.location.pathname !== this.props.location.pathname) {
      this.setState(
        {
          nowUrl: nextProps.location.pathname,
        },
        () => {
          this.activeurlnum()
        }
      )
    }
  }
  render() {
    const { routerList, activeIndex } = this.props
    return (
      <Fragment>
        <ContentHeader>
          <ContentHeaderExit onClick={this.goEnd}>退出</ContentHeaderExit>
          <ContentHeaderName>你好, 雾烟云</ContentHeaderName>
        </ContentHeader>
        <ContentHeader2>
          <ContentHeaderurl>
            {routerList.map((item, index) => {
              if (index === activeIndex) {
                if (index !== 0) {
                  return (
                    <div
                      className="urltab active"
                      key={index}
                      onClick={() => {
                        this.changeUrl(item.url)
                      }}
                    >
                      {item.name}
                      <span
                        className="closebutton"
                        onClick={(e) => {
                          this.closeUrl(e, index)
                        }}
                      >
                        X
                      </span>
                    </div>
                  )
                } else {
                  return (
                    <div
                      className="urltab active"
                      key={index}
                      onClick={() => {
                        this.changeUrl(item.url)
                      }}
                    >
                      {item.name}
                    </div>
                  )
                }
              } else {
                if (index !== 0) {
                  return (
                    <div
                      className="urltab"
                      key={index}
                      onClick={() => {
                        this.changeUrl(item.url)
                      }}
                    >
                      {item.name}
                      <span
                        className="closebutton"
                        onClick={(e) => {
                          this.closeUrl(e, index)
                        }}
                      >
                        X
                      </span>
                    </div>
                  )
                } else {
                  return (
                    <div
                      className="urltab"
                      key={index}
                      onClick={() => {
                        this.changeUrl(item.url)
                      }}
                    >
                      {item.name}
                    </div>
                  )
                }
              }
            })}
          </ContentHeaderurl>
          <ContentHeaderTime>{this.state.nowTime}</ContentHeaderTime>
        </ContentHeader2>
      </Fragment>
    )
  }
  //卸载
  componentWillUnmount() {
    clearInterval(this.dingshi)
  }
  dataformat() {
    let _this = this
    let dingshi = setInterval(() => {
      let now = new Date()
      _this.setState({
        nowTime: dateFormat(now, 'yyyy-mm-dd, h:MM:ss TT'),
      })
    }, 1000)
    _this.setState({
      dingshi,
    })
  }
  goEnd() {
    console.log('点击了退出')
    sessionStorage.clear()
    this.props.history.push({ pathname: '/' })
  }
  changeUrl(arg) {
    console.log(arg)
    console.log('改变路由')
    this.props.history.push({ pathname: arg })
  }
  closeUrl(e, value) {
    e.stopPropagation()
    console.log(value)
    this.props.handleClick(value)
    let sessiondata = JSON.parse(sessionStorage.getItem('urldata'))
    sessiondata.splice(value, 1)
    sessionStorage.setItem('urldata', JSON.stringify(sessiondata))
    //判断选中的条件下删除
    if (this.props.activeIndex === value) {
      if (sessiondata.length !== 1) {
        this.props.history.push({ pathname: sessiondata[value - 1].url })
      }
    } else {
      //非选中的条件下删除
      this.activeurlnum()
    }
  }
  activeurlnum() {
    let now_url = this.state.nowUrl || this.props.location.pathname //因为刷新,还有点击
    console.log(now_url)
    let sessionresult = JSON.parse(sessionStorage.getItem('urldata'))
    let result_num = 0
    for (let i = 0; i < sessionresult.length; i++) {
      if (sessionresult[i].url === now_url) {
        console.log(i)
        result_num = i
      }
    }
    console.log(result_num)
    this.props.changeActiveIndex(result_num)
  }
}

const mapStateToProps = (state) => {
  return {
    activeIndex:
      state.activeIndex === 0
        ? parseInt(sessionStorage.getItem('urlindex'))
        : state.activeIndex,
    routerList:
      state.routerData.length === 1
        ? JSON.parse(sessionStorage.getItem('urldata'))
        : state.routerData,
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    handleClick(value) {
      const action = ACTION_DELETE_ROUTER(value)
      dispatch(action)
    },
    changeActiveIndex(value) {
      console.log('进来了')
      sessionStorage.setItem('urlindex', value)
      const action = ACTION_CHANGE_ACTIVE_INDEX(value)
      dispatch(action)
    },
  }
}
//最后利用store挂钩

export default connect(
  mapStateToProps, //这里面放的是数据
  mapDispatchToProps //里面放的是操作的数据的方法
)(withRouter(HeaderComponent))
